<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="height: 800px ; width: 80%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-input-number v-show="false" v-model="formData.bankId"/>
      <el-form-item label="题目文本" prop="questionText">
        <el-input v-model="formData.questionText" placeholder="请输入题目文本"/>
      </el-form-item>
      <el-form-item label="题目类型" prop="questionType">
        <el-select v-model="formData.questionType" placeholder="请选择题目类型"
                   @change="changeQuestionType">
          <el-option
            v-for="item in questionTypeOptions"
            :key="item.value"
            :label="item.text"
            :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="难度级别" prop="difficultyLevel">
        <el-rate v-model="formData.difficultyLevel" :max="5" show-text
                 :texts="['简单', '一般', '中等', '困难', '极难']"/>
      </el-form-item>
      <el-form-item label="题目链接" prop="questionUrl">
        <el-input v-model="formData.questionUrl" placeholder="请输入题目链接"/>
      </el-form-item>
      <el-form-item v-if="formData.questionType === 1||formData.questionType === 2">
        <el-button @click="addOption">添加选项</el-button>
      </el-form-item>
      <div v-if="formData.questionType === 2 || formData.questionType === 1">
        <div v-for="(option,index) in formData.selectedOptions" :key="index"
             style="white-space: nowrap">
          <div style="white-space: nowrap; margin: 5px;padding: 10px">
            <el-tag style="padding: 5px">{{ option.label }}</el-tag>
            :
            <el-input style="width: 80%  ;padding: 5px" v-model="option.optionText"
                      placeholder="请输入选项文本"/>
            <el-tag style="padding: 5px; color: red" @click="removeOption(option.label)">删除选项
            </el-tag>
            <el-checkbox style="padding: 5px" v-model="option.correct"
                         @click="selectCorrect(option.correct,option.label)">正确选项
            </el-checkbox>
          </div>
        </div>
        <el-form-item label="正确答案：">
          <el-tag v-for="item in correctOptions" :key="item.value">{{ item.label }}</el-tag>
        </el-form-item>
      </div>
      <el-form-item v-if="formData.questionType === 3" label="是否正确">
        <el-switch v-model="formData.corrected" active-text="正确" active-value="1"
                   inactive-text="错误" inactive-value="0"/>
      </el-form-item>
      <el-form-item v-if="formData.questionType !== 1 && formData.questionType !== 2"
                    label="答案关键字">
        <el-input v-model="formData.answerKey"/>
      </el-form-item>
      <el-form-item v-if="formData.questionType !== 1 && formData.questionType !== 2"
                    label="答案地址">
        <el-input v-model="formData.answerUrl"/>
      </el-form-item>
      <el-form-item label="解析">
        <el-input v-model="formData.analysis"/>
      </el-form-item>
      <el-form-item label="解析地址">
        <el-input v-model="formData.analysisUrl"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {QuestionApi, QuestionVO} from '@/api/exam/question'
import {number} from "echarts";

/** 试题 表单 */
defineOptions({name: 'QuestionForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const selectedOptions = ref([
  {optionText: '选项1', value: 1, correct: false, label: 'A', id: undefined, optionUrl: ''},
  {optionText: '选项2', value: 2, correct: false, label: 'B', id: undefined, optionUrl: ''},
  {optionText: '选项3', value: 3, correct: false, label: 'C', id: undefined, optionUrl: ''}
])

const questionTypeOptions = ref([
  {text: '单选', value: 1,},
  {text: '多选', value: 2,},
  {text: '判断', value: 3,},
  {text: '填空', value: 4,},
  {text: '简答', value: 5,},
  {text: '问答', value: 6,},
  {text: '计算', value: 7,}
])
const correctOptions = ref([]);
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  bankId: -1,
  questionText: undefined,
  questionType: undefined,
  difficultyLevel: 2,
  questionUrl: undefined,
  version: undefined,
  corrected: '0',
  answerKey: '',
  answerUrl: '',
  analysis: '',
  analysisUrl: '',
  selectedOptions: []
})
const formRules = reactive({
  questionText: [{required: true, message: '题目文本不能为空', trigger: 'blur'}],
  questionType: [{required: true, message: '题目类型不能为空', trigger: 'change'}],
  difficultyLevel: [{required: true, message: '题目难度级别不能为空', trigger: 'blur'}],
  version: [{required: true, message: '版本号不能为空', trigger: 'blur'}],
})
const formRef = ref() // 表单 Ref
const letter = ref(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'])

function addOption() {
  if (formData.value.selectedOptions.length < 13) {
    let label = letter.value[formData.value.selectedOptions.length]
    formData.value.selectedOptions.push({
      label: label,
      optionText: '新选项',
      value: selectedOptions.value.length + 100,
      correct: false,
      optionUrl: '',
    });
  }
}

function changeQuestionType() {
  if (formData.value.questionType === 1 || formData.value.questionType === 2){
    if(formData.value.selectedOptions==null || formData.value.selectedOptions.length==0){
      formData.value.selectedOptions = selectedOptions.value;
    }
  }
}

function selectCorrect(correct, label) {
  if (formData.value.questionType === 2) {
    correctOptions.value = formData.value.selectedOptions.filter(item => item.correct === true || (!correct && item.label === label));
  } else {
    for (let j = 0; j < formData.value.selectedOptions.length; j++) {
      if (selectedOptions.value[j].correct) {
        selectedOptions.value[j].correct = false;
      }
    }
    correctOptions.value = formData.value.selectedOptions.filter(item => !correct && item.label === label);
  }
}

function removeOption(label) {
  formData.value.selectedOptions = formData.value.selectedOptions.filter(item => item.label !== label);
  correctOptions.value = correctOptions.value.filter(item => item.label !== label);
  setOptionsTags();
}

function setOptionsTags() {
  if ((formData.value.questionType === 1 || formData.value.questionType === 2) && (formData.value.selectedOptions.length > 0)){
    for (let i = 0; i < formData.value.selectedOptions.length; i++) {
      formData.value.selectedOptions[i].label = letter.value[i]
    }
  }
}

/** 打开弹窗 */
const open = async (type: string, bankId?: number, id?: number) => {
  console.log("bankId" + bankId)
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await QuestionApi.getQuestion(id)
      formData.value.corrected = formData.value.corrected!=null? String(formData.value.corrected):'0';
      setOptionsTags();
    } finally {
      formLoading.value = false
    }
  }
  if (bankId != null) {
    formData.value.bankId = bankId;
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as QuestionVO
    if (formType.value === 'create') {
      await QuestionApi.createQuestion(data)
      message.success(t('common.createSuccess'))
    } else {
      await QuestionApi.updateQuestion(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    bankId: -1,
    questionText: undefined,
    questionType: undefined,
    difficultyLevel: 2,
    questionUrl: undefined,
    version: undefined,
    corrected: '0',
    answerKey: '',
    answerUrl: '',
    analysis: '',
    analysisUrl: '',
    selectedOptions: []
  }
  formRef.value?.resetFields()
}
</script>
